import {
    REMOVE,
    ATTR,
    SPLICE,
    TEXT
} from './patchesType';
import Element from './Element';
import {render} from './vDom';

let rnIndex = 0,
    allPatches = {};

function doPatch(rDom, patches) {
    allPatches = patches;
    rNodeWalk(rDom);
}

function rNodeWalk(rDom) {
    const patch = allPatches[rnIndex++],
        childNodes = rDom.childNodes;
    [...childNodes].map(child => {
        rNodeWalk(child);
    });
    if (patch) {
        patchAction(rDom, patch);
    }
}

function patchAction(rNode, rnPatchs) {
    rnPatchs.map(patch => {
        switch (patch.type) {
            case TEXT:
                rNode.textContent = patch.text;
                break;
            case REMOVE:
                rNode.parentNode.removeChild(rNode);
                break;
            case ATTR:
                for (let key in patch.attr) {
                    const value = patch.attr[key];
                    if (value) {
                        rNode.setAttribute(key, patch.attr[key]);
                    } else {
                        rNode.removeAttribute(key);
                    }
                }
                break;
            case SPLICE:
                const newNode = patch.newNode instanceof Element ? render(patch.newNode):document.createTextNode(patch.newNode);
                rNode.parentNode.replaceChild(newNode, rNode);
                break;
            default:
                break;
        }
    })
}

export default doPatch;